#include "os_helper.h"

#include <bit>

namespace os_helper {
#if (defined(__cplusplus) && __cplusplus >= 202002L ) || (defined(_MSVC_LANG) && _MSVC_LANG >= 202002L)
	bool is_intel_byte_ordering()
	{
		return std::endian::native == std::endian::little;
	}
#else

	bool is_intel_byte_ordering()
	{
		uint32_t num = 0x12346578;
		uint8_t* p = reinterpret_cast<uint8_t*>(&num);

		if (*p == 0x78) {
			return true;
		}
		return false;
	}
#endif

	uint16_t motorola_to_intel(uint16_t num)
	{
		uint16_t low = num >> 8 & 0xFF;
		uint16_t high = num & 0xFF;
		return (high << 8 | low);
	}
	uint32_t motorola_to_intel(uint32_t num)
	{
		size_t nhalfbytes = sizeof(num) >> 1;
		for (int i = 0; i < nhalfbytes; i++) {
			uint8_t& low = byte_of_number(num, i);
			uint8_t& high = byte_of_number(num, sizeof(num) - i - 1);
			std::swap(low, high);
		}
		return num;
	}
	uint64_t motorola_to_intel(uint64_t num)
	{
		size_t nhalfbytes = sizeof(num) >> 1;
		for (int i = 0; i < nhalfbytes; i++) {
			uint8_t& low = byte_of_number(num, i);
			uint8_t& high = byte_of_number(num, sizeof(num) - i - 1);
			std::swap(low, high);
		}
		return num;
	}

	std::string file_suffix(const std::string& filepath)
	{
		std::string s;
		auto dotpos = filepath.find_last_of('.');
		s = filepath.substr(dotpos + 1);
		return s;
	}
	std::string simple_filename(const std::string& filepath)
	{
		std::string s;
		char separator = FILEPATH_SEPARATOR;
		auto slashpos = filepath.find_last_of(separator);
		if (slashpos != std::string::npos)
			s = filepath.substr(slashpos + 1);
		else
			s = filepath;
		return s;
	}
}
